package com.wisdudu.blank.support.widget.esptouch.helper;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.wisdudu.blank.support.util.ToastUtil;
import com.wisdudu.blank.support.widget.esptouch.EsptouchTask;
import com.wisdudu.blank.support.widget.esptouch.IEsptouchResult;
import com.wisdudu.blank.support.widget.esptouch.task.CallBackResultS;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Admin on 2015/11/12.
 */
public class EqmentAsyncTask {
    public static volatile boolean shouldStop = false;
    private static String mMac;
    private static Context mctx;
    private static CallBackResultS mresultS;
    private static EQHandler mHandler;
    private static EsptouchTask mEsptouchTask;
    private static ExecutorService executorService;
    private static EsptouchAsyncTask3 esptouchAsyncTask3;

    /***
     * 开始配置
     *
     * @param apSsid             //账号
     * @param apBssid            //相当mac
     * @param apPassword         //密码
     * @param isSsidHiddenStr    //是否隐藏 "NO" or "YES"
     * @param taskResultCountStr 默认1
     */
    public static void startUDPconfig(Context ctx, final String apSsid, final String apBssid, final String apPassword, final String isSsidHiddenStr,
                                       final String taskResultCountStr, final String Mac, CallBackResultS resultS) {
        Log.e("testq", "开始配置");
        mMac = Mac;
        mctx = ctx;
        mresultS = resultS;
        if (mHandler == null) {
            mHandler = new EQHandler();
        }
        mHandler.sendEmptyMessage(1);//开始配置
        //执行异步任务
        esptouchAsyncTask3 = new EsptouchAsyncTask3(mHandler);
        esptouchAsyncTask3.execute(apSsid, apBssid, apPassword, isSsidHiddenStr, taskResultCountStr);
    }
    public static class EQHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            if (!shouldStop) {
//                Log.i("testq","是否中断");
//                return;
//            }
            switch (msg.what) {
                case 10:
                    ToastUtil.INSTANCE.toast("二维码的设备串号和该设备的串号不一致，请检查后再试");
                    break;
                case 1:
                    if (mresultS != null)
                        mresultS.onStart("one");
                    break;
                case 2:
                    if (mresultS != null) {
                        mresultS.onScan("two");
                    }
                    break;
                case 3:
                    if (mresultS != null)
                        mresultS.onConfig("three");

                    break;
                case 4:
                    if (mresultS != null) {
                        mresultS.onFail("配置失败");
                    }
                    break;
                case 5:
                    try {
                        JSONObject object = (JSONObject) msg.obj;
                        String user = object.getString("user");
                        String password = object.getString("password");
                        String type = object.getString("type");
                        if (mresultS != null) {
                            System.out.println("------ssss---------four");
                            mresultS.onFinish(user, password, type, "four");
                        } else {
                            System.out.println("------ffff---------four");
                            mresultS.onFail("配置失败");
                        }
                    } catch (JSONException e) {
                        System.out.println("------catch---------four");
                        if (mresultS != null)
                            mresultS.onFail("配置失败");
                        e.printStackTrace();
                    }
                    break;
                case 12:
                    Log.i("testq", "中断msocketTask+handler");
                    mHandler.sendEmptyMessage(4);
                    break;
                default:
                    break;
            }
        }
    }
    /**
     * Another Stop
     */
    public static void stopE() {
        if(executorService ==null){
            executorService = Executors.newSingleThreadExecutor();
        }
//        executorService.shutdownNow();
        Runnable r=new Runnable(){
            @Override
            public void run() {
                if (mEsptouchTask != null && !mEsptouchTask.isCancelled()) {
                    Log.i("testq", "中断配置");
                    mEsptouchTask.interrupt();
                }
            }
        };
        executorService.execute(r);
    }
    private static class EsptouchAsyncTask3 extends AsyncTask<String, Void, List<IEsptouchResult>> {
        // private ProgressDialog mProgressDialog;

        //public IEsptouchTask mEsptouchTask;
        // without the lock, if the user tap confirm and cancel quickly enough,
        // the bug will arise. the reason is follows:
        // 0. task is starting created, but not finished
        // 1. the task is cancel for the task hasn't been created, it do nothing
        // 2. task is created
        // 3. Oops, the task should be cancelled, but it is running
        private final Object mLock = new Object();
        Handler mhandler;

        public EsptouchAsyncTask3(Handler handler) {
            this.mhandler = handler;
        }

        @Override
        protected List<IEsptouchResult> doInBackground(String... params) {
            int taskResultCount = -1;
            shouldStop=false;
            Log.e("testq", "第2步配置");
            if (mhandler != null) {
                mhandler.sendEmptyMessage(2);
            }
            taskResultCount = Integer.parseInt(params[4]);
            boolean isSsidHidden = params[3].equals("YES");
            mEsptouchTask = new EsptouchTask(params[0], params[1], params[2], isSsidHidden, mctx);
            if(shouldStop){
                return null;
            }
            return mEsptouchTask.executeForResults(taskResultCount);
//            }
        }

        @Override
        protected void onPostExecute(List<IEsptouchResult> result) {
//            taskHandler.removeCallbacks(stopEspTask);
            IEsptouchResult firstResult = result.get(0);
            // check whether the task is cancelled and no results received
            if (firstResult.isCancelled()) {
                //直接发送消息4，配置失败
                Log.e("testq", "第3步配置被中断");
//                mhandler.sendEmptyMessage(4);
                return;
            }
            if(shouldStop){
                return;
            }
            Log.e("testq", "第3步配置");
            mhandler.sendEmptyMessage(3);
            init(mhandler, mMac);
        }
    }

    public static void init(Handler handler, String Mac) {
        new ServerSocketS().serviceSingle(handler, Mac);//第3步
    }
}
